import logging
from logging.handlers import RotatingFileHandler

from flask import redirect
from flask.ext.session import Session
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.wtf import CSRFProtect
from redis import StrictRedis

from flask import Flask

from config import Config

redis_store = None
db = None


def create_app():
    app = Flask(__name__)

    # 导入配置类
    app.config.from_object(Config)

    global db
    db = SQLAlchemy(app)

    log_file()

    global redis_store
    redis_store = StrictRedis(host=Config.REDIS_HOST, port=Config.REDIS_PORT, decode_responses=True)

    Session(app)

    # CSRFProtect(app)

    from api_v1.house_views import house_blueprint
    from api_v1.order_views import order_blueprint
    from api_v1.user_views import user_blueprint
    from html_views import html_blueprint
    app.register_blueprint(house_blueprint)
    app.register_blueprint(order_blueprint)
    app.register_blueprint(user_blueprint)
    app.register_blueprint(html_blueprint)
    # print(app.url_map)

    #重定向到首页
    @app.errorhandler(404)
    def page_not_found(e):
        return redirect('/')

    return app


#日志函数
def log_file():
    # 设置日志的记录等级
    logging.basicConfig(level=logging.DEBUG)  # 调试debug级
    # 创建日志记录器，指明日志保存的路径、每个日志文件的最大大小、保存的日志文件个数上限
    file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)
    # 创建日志记录的格式 日志等级 输入日志信息的文件名 行数 日志信息
    formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')
    # 为刚创建的日志记录器设置日志记录格式
    file_log_handler.setFormatter(formatter)
    # 为全局的日志工具对象（flask app使用的）添加日志记录器
    logging.getLogger().addHandler(file_log_handler)